import telebot
import json
import re 
import xml.etree.ElementTree as ET
import os 

import logging
logging.basicConfig(level=logging.INFO, filename="application_log.log", filemode="a")


settings = {}
with open('settings.json') as f:
    settings = json.load(f)

allowed_chats = settings["telegram.allow.chats"]

bot = telebot.TeleBot(settings["telegram.bot.token"])

from tools.licgen.licensegenerator import LicenseGenerator
from tools.gigachat.license_req_handler import LicenseReqHandler

lc_handler = LicenseReqHandler(settings)
lc_generator  = LicenseGenerator(settings)

find_patterns = (
    "тестовую лицензию", 
    "лицензию",
    "лицензия",
    "коммерческую лицензию", 
    "борис лицензия"
)

def has_pattern(text):
    for pattern in find_patterns:
        if pattern in text:
            return True
    return False


def licence_info(xml_data):
    root = ET.fromstring(xml_data)
    
    licence_key = root.find('LicenceKey').text
    order_date = root.find('OrderDate').text
    start_date = root.find('StartDate').text
    end_date = root.find('EndDate').text
    active_period = root.find('ActivePeriod').text
    computer_id = root.find('ComputerID').text if root.find('ComputerID') is not None else '-'
    company = root.find('Company').text
    uuid_company = root.find('UuidCompany').text
    product_id = root.find('ProductID').text
    count_license = root.find('CountLicense').text
    
    output = f"Licence Key: {licence_key}\n" \
             f"Order Date: {order_date}\n" \
             f"Start Date: {start_date}\n" \
             f"End Date: {end_date}\n" \
             f"Active Period: {active_period} days\n" \
             f"Computer ID: {computer_id}\n" \
             f"Company: {company}\n" \
             f"UUID Company: {uuid_company}\n" \
             f"Product ID: {product_id}\n" \
             f"Count License: {count_license}\n"
    
    return output



def check_permissions(msg):
    if str(msg.chat.id) in allowed_chats:
        return True
    
    logging.warning(f"Drop chat id:  {msg.chat.id}")
    return False


@bot.message_handler(func=check_permissions)
def on_message(message):
    lower_text: str = message.text.lower()
    
    try:
        if has_pattern(lower_text):
            res: str = lc_handler.process(message.text)
            s = res.find("JSON_REQ_START") + len("JSON_REQ_START")
            e = res.find("JSON_REQ_END")
            res = res[s:e]
            
            stdout, stderr, filename = lc_generator.gen(json.loads(res))
            if stderr:
                logging.error(stderr)
            
            root = ET.fromstring(stdout)
            licence_key = root.find('LicenceKey').text
            order_date = root.find('OrderDate').text
            start_date = root.find('StartDate').text
            end_date = root.find('EndDate').text
            active_period = root.find('ActivePeriod').text
            computer_id = root.find('ComputerID').text if root.find('ComputerID') is not None else '-'
            company = root.find('Company').text
            uuid_company = root.find('UuidCompany').text
            product_id = root.find('ProductID').text
            count_license = root.find('CountLicense').text
    
            output = f"Licence Key: {licence_key}\n" \
                    f"Order Date: {order_date}\n" \
                    f"Start Date: {start_date}\n" \
                    f"End Date: {end_date}\n" \
                    f"Active Period: {active_period} days\n" \
                    f"Computer ID: {computer_id}\n" \
                    f"Company: {company}\n" \
                    f"UUID Company: {uuid_company}\n" \
                    f"Product ID: {product_id}\n" \
                    f"Count License: {count_license}\n"
            
            bot.send_message(chat_id=message.chat.id, text=output)
            
            with open(filename, 'rb') as f:
                bot.send_document(message.chat.id, f)
            os.remove(filename)
            
            logging.info(f"Сгенерирована лицензия: {output.replace('\n', ' ')}")
            
    except Exception as e:
        logging.error(e)
        
logging.info("Service started!")
bot.polling()

